package com.lpdemilis.pokermanager;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EventActivity extends Activity implements MyAsyncListener {
	private int eventid;
	private Event event;
	private User user;
	private int groupindex;
	protected CustomHttpClient client;
	private TextView eventNameTextView;
	private TextView eventTimestartTextView;
	private TextView eventTimeconfirmTextView;
	private TextView eventMaxUsersTextView;
	private TextView eventMinUsersTextView;
	private TextView eventPlaceTextView;
	private TextView eventDescriptionTextView;
	private LinearLayout eventConfirmationLinearLayout;
	private LinearLayout eventConfirmationButtonsLinearLayout;
	private LinearLayout eventConfirmedUsersLinearLayout;
	private LinearLayout eventDisconfirmedUsersLinearLayout;
	private Button removeConfirmationButton;
	private Button removeDisconfirmationButton;
	private Button confirmButton;
	private Button disconfirmButton;
	private Button confirmOtherUserButton;
	protected String SERVER_URL;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event);
		
		if (Build.MANUFACTURER.equals("unknown")){
			SERVER_URL = this.getString(R.string.URL_local);
		}else{
			SERVER_URL = this.getString(R.string.URL);
		}

		eventid = getIntent().getIntExtra("eventid", 0);
		user = (User) getIntent().getSerializableExtra("user");
		groupindex = getIntent().getIntExtra("groupindex", 0);

		eventNameTextView = (TextView) findViewById(R.id.eventNameTextView);
		eventTimestartTextView = (TextView) findViewById(R.id.eventTimestartTextView);
		eventTimeconfirmTextView = (TextView) findViewById(R.id.eventTimeconfirmTextView);
		eventMaxUsersTextView = (TextView) findViewById(R.id.eventMaxUsersTextView);
		eventMinUsersTextView = (TextView) findViewById(R.id.eventMinUsersTextView);
		eventPlaceTextView = (TextView) findViewById(R.id.eventPlaceTextView);
		eventDescriptionTextView = (TextView) findViewById(R.id.eventDescriptionTextView);
		eventConfirmationLinearLayout = (LinearLayout) findViewById(R.id.eventConfirmationLinearLayout);
		eventConfirmationButtonsLinearLayout = (LinearLayout) findViewById(R.id.eventConfirmationButtonsLinearLayout);
		eventConfirmedUsersLinearLayout = (LinearLayout) findViewById(R.id.eventConfirmedUsersLinearLayout);
		eventDisconfirmedUsersLinearLayout = (LinearLayout) findViewById(R.id.eventDisconfirmedUsersLinearLayout);

		getEvent();
	}

	public enum ActionsEnum {
		getEvent, confirmUser, error;
	}

	@Override
	public void executeReturn(String returnValue) {
		String[] returnArray;
		returnArray = returnValue.split("##");

		ActionsEnum action;

		try {
			action = ActionsEnum.valueOf(returnArray[0]);
		} catch (Exception e) {
			action = ActionsEnum.error;
		}

		switch (action) {
		case getEvent:
			getEventReturn(returnArray);
			break;
		case confirmUser:
			confirmUserReturn(returnArray);
			break;
		case error:
			errorReturn(returnArray);
			break;
		}
	}

	private void errorReturn(String[] returnArray) {
		// TODO Auto-generated method stub
		getEvent();
	}

	private void getEventReturn(String[] returnArray) {
		if (returnArray.length <= 1) {

		} else {
			event = new Event();
			event.setId(Integer.parseInt(returnArray[1]));
			event.setName(returnArray[2]);
			event.setDescription(returnArray[3]);
			event.setGroupid(Integer.parseInt(returnArray[4]));
			event.setUserid(Integer.parseInt(returnArray[5]));
			event.setPlace(returnArray[6]);
			Date timestart = new Date(Long.valueOf(returnArray[7]));
			event.setTimestart(timestart);
			Date timeconfirm = new Date(Long.valueOf(returnArray[8]));
			event.setTimeconfirm(timeconfirm);
			event.setMaxusers(Integer.parseInt(returnArray[9]));
			event.setMinusers(Integer.parseInt(returnArray[10]));
			event.setRoundtime(Integer.parseInt(returnArray[11]));
			event.setBuyinvalue(Double.valueOf(returnArray[12]));
			event.setRebuyvalue(Double.valueOf(returnArray[13]));
			event.setAddonvalue(Double.valueOf(returnArray[14]));

			String[] prize = returnArray[15].split(",");
			ArrayList<Number> prizeArrayList = new ArrayList<Number>();

			if (!prize[0].equals("")) {
				for (int i = 0; i < prize.length; i++) {
					prizeArrayList.add(Double.valueOf(prize[i]));
				}
			}
			event.setPrize(prizeArrayList);

			String[] point = returnArray[16].split(",");
			ArrayList<Number> pointArrayList = new ArrayList<Number>();

			if (!point[0].equals("")) {
				for (int i = 0; i < point.length; i++) {
					pointArrayList.add(Double.valueOf(point[i]));
				}
			}
			event.setPoint(pointArrayList);

			event.setPrizemod(Integer.parseInt(returnArray[17]));

			String[] blinds = returnArray[18].split(";");

			ArrayList<Number> smallBlindsArrayList = new ArrayList<Number>();
			ArrayList<Number> bigBlindsArrayList = new ArrayList<Number>();

			if (!blinds[0].equals("")) {
				String[] smallBlinds = blinds[0].split(",");
				String[] bigBlinds = blinds[1].split(",");

				for (int i = 0; i < smallBlinds.length; i++) {
					smallBlindsArrayList
							.add(Double.parseDouble(smallBlinds[i]));
					bigBlindsArrayList.add(Double.parseDouble(bigBlinds[i]));
				}
			}

			event.setSmallBlinds(smallBlindsArrayList);
			event.setBigBlinds(bigBlindsArrayList);

			event.setCurrentround(Integer.parseInt(returnArray[19]));
			event.setCurrenttime(Integer.parseInt(returnArray[20]));
			event.setTotalprize(Double.valueOf(returnArray[21]));
			event.setFinalized(Boolean.valueOf(returnArray[22]));
			Date timemodified = new Date(Long.valueOf(returnArray[23]));
			event.setTimemodified(timemodified);

			String[] confirmeduserids = returnArray[24].trim().split(",");

			ArrayList<Number> confirmeduseridsArrayList = new ArrayList<Number>();

			if (!confirmeduserids[0].equals("")) {
				for (int i = 0; i < confirmeduserids.length; i++) {
					confirmeduseridsArrayList.add(Integer
							.valueOf(confirmeduserids[i]));
				}
			}

			event.setConfirmeduseridsArrayList(confirmeduseridsArrayList);

			String[] confirmedusernames = returnArray[25].trim().split(",");

			ArrayList<String> confirmedusernamesArrayList = new ArrayList<String>();

			if (!confirmedusernames[0].equals("")) {
				for (int i = 0; i < confirmedusernames.length; i++) {
					confirmedusernamesArrayList.add(confirmedusernames[i]);
				}
			}

			event.setConfirmedusernamesArrayList(confirmedusernamesArrayList);

			String[] timeconfirmations = returnArray[26].trim().split(",");

			ArrayList<Date> timeconfirmationsArrayList = new ArrayList<Date>();

			if (!timeconfirmations[0].equals("")) {
				for (int i = 0; i < timeconfirmations.length; i++) {
					timeconfirmationsArrayList.add(new Date(Long
							.valueOf(timeconfirmations[i])));
				}
			}

			event.setTimeconfirmationsArrayList(timeconfirmationsArrayList);

			String[] confirmations = returnArray[27].trim().split(",");

			ArrayList<Number> confirmationsArrayList = new ArrayList<Number>();

			if (!confirmations[0].equals("")) {
				for (int i = 0; i < confirmations.length; i++) {
					confirmationsArrayList.add(Integer
							.valueOf(confirmations[i]));
				}
			}

			event.setConfirmationsArrayList(confirmationsArrayList);

			event.setUserCanEdit(Boolean.valueOf(returnArray[28].trim()));

			updateInterface();
		}
	}

	private void confirmUserReturn(String[] returnArray) {
		getEvent();
	}

	private void updateInterface() {
		// update interface
		eventNameTextView.setText(event.getName());
		eventTimestartTextView.setText(event.getTimestart().toString());
		eventTimeconfirmTextView.setText(event.getTimeconfirm().toString());
		eventMaxUsersTextView.setText(String.valueOf(event.getMaxusers()));
		eventMinUsersTextView.setText(String.valueOf(event.getMinusers()));
		eventPlaceTextView.setText(event.getPlace());
		eventDescriptionTextView.setText(event.getDescription());

		int myConfirmationIndex = event.getConfirmeduseridsArrayList().indexOf(
				user.getId());

		Calendar currenttime = Calendar.getInstance();
		Date date = new Date((currenttime.getTime()).getTime());

		if (event.getTimeconfirm().before(date)) {
			TextView timeconfirmEnded = new TextView(this);
			timeconfirmEnded.setText(R.string.timeconfirmEnded);
			eventConfirmationLinearLayout.addView(timeconfirmEnded, 0);
		}

		if ((event.getTimeconfirm().after(date)) || (event.getUserCanEdit())) {
			int index = event.getConfirmationsArrayList()
					.get(myConfirmationIndex).intValue();
			switch (index) {
			case 0:
				removeDisconfirmationButton = new Button(this);
				removeDisconfirmationButton.setText(this
						.getString(R.string.removeDisconfirmation));
				removeDisconfirmationButton
						.setOnClickListener(removeDisconfirmationButtonClickListener);
				eventConfirmationButtonsLinearLayout.removeAllViewsInLayout();
				eventConfirmationButtonsLinearLayout
						.addView(removeDisconfirmationButton);
				break;
			case 1:
				removeConfirmationButton = new Button(this);
				removeConfirmationButton.setText(this
						.getString(R.string.removeConfirmation));
				removeConfirmationButton
						.setOnClickListener(removeConfirmationButtonClickListener);
				eventConfirmationButtonsLinearLayout.removeAllViewsInLayout();
				eventConfirmationButtonsLinearLayout
						.addView(removeConfirmationButton);
				break;
			default:
				confirmButton = new Button(this);
				confirmButton.setText(this.getString(R.string.confirm));
				confirmButton.setOnClickListener(confirmButtonClickListener);
				disconfirmButton = new Button(this);
				disconfirmButton.setText(this.getString(R.string.disconfirm));
				disconfirmButton
						.setOnClickListener(disconfirmButtonClickListener);
				eventConfirmationButtonsLinearLayout.removeAllViewsInLayout();
				eventConfirmationButtonsLinearLayout.addView(confirmButton);
				eventConfirmationButtonsLinearLayout.addView(disconfirmButton);
				break;
			}

			if (event.getUserCanEdit()) {
				//esta inserindo o botao com layout zuado
				confirmOtherUserButton = new Button(this);
				confirmOtherUserButton.setText(this
						.getString(R.string.confirmOtherUser));
				confirmOtherUserButton.setOnClickListener(confirmOtherUserButtonClickListener);
				if (event.getTimeconfirm().before(date)) {
					if(eventConfirmationLinearLayout.getChildCount() == 3){
						eventConfirmationLinearLayout.removeViewAt(2);
					}
				}else{
					if(eventConfirmationLinearLayout.getChildCount() == 2){
						eventConfirmationLinearLayout.removeViewAt(1);
					}
				}
				eventConfirmationLinearLayout.addView(confirmOtherUserButton);
			}
		}

		ArrayList<String> confirmedusersArrayList = new ArrayList<String>();

		ArrayList<LinearLayout> confirmedUsersLinearLayouts = new ArrayList<LinearLayout>();
		ArrayList<TextView> confirmedUsersNamesTextViews = new ArrayList<TextView>();
		ArrayList<TextView> confirmedUsersTimesTextViews = new ArrayList<TextView>();

		eventConfirmedUsersLinearLayout.removeAllViewsInLayout();
		eventDisconfirmedUsersLinearLayout.removeAllViewsInLayout();

		for (int i = 0; i < event.getConfirmeduseridsArrayList().size(); i++) {
			confirmedusersArrayList.add(event.getConfirmedusernamesArrayList()
					.get(i));
			confirmedusersArrayList.add(event.getTimeconfirmationsArrayList()
					.get(i).toString());

			confirmedUsersLinearLayouts.add(i, new LinearLayout(this));

			confirmedUsersNamesTextViews.add(i, new TextView(this));
			int px = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_SP, 180, getResources()
							.getDisplayMetrics());
			confirmedUsersNamesTextViews.get(i).setWidth(px);
			confirmedUsersNamesTextViews.get(i).setText(
					event.getConfirmedusernamesArrayList().get(i));

			confirmedUsersTimesTextViews.add(i, new TextView(this));
			confirmedUsersTimesTextViews.get(i).setText(
					event.getTimeconfirmationsArrayList().get(i).toString());

			confirmedUsersLinearLayouts.get(i).addView(
					confirmedUsersNamesTextViews.get(i));
			confirmedUsersLinearLayouts.get(i).addView(
					confirmedUsersTimesTextViews.get(i));

			if (event.getConfirmationsArrayList().get(i).equals(1)) {
				eventConfirmedUsersLinearLayout
						.addView(confirmedUsersLinearLayouts.get(i));
			} else if (event.getConfirmationsArrayList().get(i).equals(0)) {
				eventDisconfirmedUsersLinearLayout
						.addView(confirmedUsersLinearLayouts.get(i));
			}

		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(EventActivity.this, MainActivity.class);
		intent.putExtra("groupindex", groupindex);
		intent.putExtra("user", user);
		EventActivity.this.startActivity(intent);
		EventActivity.this.finish();
	}

	View.OnClickListener removeConfirmationButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			confirmUser(event.getId(), user.getId(), 2, user.getId());
		}
	};

	View.OnClickListener removeDisconfirmationButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			confirmUser(event.getId(), user.getId(), 2, user.getId());
		}
	};

	View.OnClickListener confirmButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			confirmUser(event.getId(), user.getId(), 1, user.getId());
		}
	};

	View.OnClickListener disconfirmButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			confirmUser(event.getId(), user.getId(), 0, user.getId());

		}
	};
	
	View.OnClickListener confirmOtherUserButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			
		}
	};

	public void getEvent() {
		try {
			client = new CustomHttpClient(this);
			String action = ActionsEnum.getEvent.toString();
			String paramName1 = "eventid";
			String paramValue1 = String.valueOf(eventid);
			String paramName2 = "userid";
			String paramValue2 = String.valueOf(user.getId());
			client.execute(SERVER_URL, action, paramName1,
					paramValue1, paramName2, paramValue2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void confirmUser(int eventid, int userid, int presence,
			int usermodified) {
		try {
			client = new CustomHttpClient(this);
			String action = ActionsEnum.confirmUser.toString();
			String paramName1 = "eventid";
			String paramValue1 = String.valueOf(eventid);
			String paramName2 = "userid";
			String paramValue2 = String.valueOf(userid);
			String paramName3 = "presence";
			String paramValue3 = String.valueOf(presence);
			String paramName4 = "usermodified";
			String paramValue4 = String.valueOf(usermodified);
			client.execute(SERVER_URL, action, paramName1,
					paramValue1, paramName2, paramValue2, paramName3,
					paramValue3, paramName4, paramValue4);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
